

use clap::Args;
use serde::{Deserialize, Serialize};
use wtask_base::{app::get_wtask_data_dir, error::WResult};

use crate::{task::utils::meta::{TaskList, TaskMeta}, utils::AppTrait};




#[derive(Debug, Clone, Serialize, Deserialize, Args)]
pub struct AppTaskList {
    /// 根据app筛选
    pub(crate) app: Option<String>,

    /// 根据version筛选
    pub(crate) version: Option<String>,

    /// 展示meta，默认展示任务列表
    #[arg(long)]
    pub(crate) meta: bool,
}

impl AppTrait for AppTaskList {
    type Status = ();
    type Res = TaskList;

    async fn server_handle_single(self) -> WResult<TaskList> {
        let dir_task = get_wtask_data_dir("task", false)?;
        let apps = dir_task.read_dir().unwrap().map(| v | {
            v.unwrap().path()
        });
        let apps = if let Some(app) = self.app {
            let version = if let Some(version) = self.version {
                version
            } else {
                "".to_string()
            };
            let prefix = format!("{app}.{version}");
            apps.filter(| v | {
                v.file_name().unwrap().to_str().unwrap().starts_with(&prefix)
            }).map(| v |{
                TaskMeta::new(&v).unwrap()
            }).collect::<Vec<_>>()
        } else {
            apps.map(| v |{
                TaskMeta::new(&v).unwrap()
            }).collect::<Vec<_>>()
        };
        Ok(TaskList { apps, meta: self.meta })
    }
}

